package handler

import (
	"github.com/gin-gonic/gin"
	"watermelon/client/client"
	"watermelon/client/request"
	user "watermelon/common/proto"
	"watermelon/pkg"
)

func SendSms(c *gin.Context) {
	var data request.SendSms
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "请求失败！无法找到请求的资源",
			"data": nil,
		})
		return
	}
	sms, err := client.SendSms(c, &user.SendSmsReq{
		Mobile: data.Mobile,
		Source: data.Source,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"msg":  "请求失败！服务器内部错误",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "服务器响应正常",
		"data": sms,
	})

}

func UserLogin(c *gin.Context) {
	var data request.UserLogin
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "请求失败！无法找到请求的资源",
			"data": nil,
		})
		return
	}
	login, err := client.UserLogin(c, &user.UserLoginReq{
		Mobile: data.Mobile,
		Code:   data.Code,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"msg":  "请求失败！服务器内部错误",
			"data": nil,
		})
		return
	}
	claims := pkg.CustomClaims{ID: uint(login.Greet)}
	token, err := pkg.NewJWT("2211a").CreateToken(claims)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"msg":  "请求失败！服务器内部错误1",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "服务器响应正常",
		"data": map[string]interface{}{
			"token": token,
		},
	})
}

func UserItem(c *gin.Context) {
	userId := c.GetUint("userId")
	item, err := client.UserItem(c, &user.UserItemReq{UserId: int64(userId)})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"msg":  "请求失败！服务器内部错误",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "服务器响应正常",
		"data": item,
	})
}

func UserCar(c *gin.Context) {
	var data request.UserCar
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "请求失败！无法找到请求的资源",
			"data": nil,
		})
		return
	}
	userId := c.GetUint("userId")
	car, err := client.UserCar(c, &user.UserCarReq{
		UserId:      int64(userId),
		Destination: data.Destination,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"msg":  "请求失败！服务器内部错误",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "服务器响应正常",
		"data": car,
	})
}

func WxLogin(c *gin.Context) {
	c.Query("scope")
	c.Query("")
}

func ForgetPassword(c *gin.Context) {
	var data request.ForgetPassword
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "请求失败！无法找到请求的资源",
			"data": nil,
		})
		return
	}
	userId := c.GetUint("userId")
	passwrod, err := client.ForgetPasswrod(c, &user.ForgetPasswordReq{
		UserId:   int64(userId),
		Password: data.Password,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"msg":  "请求失败！服务器内部错误",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "服务器响应正常",
		"data": passwrod,
	})
}
